package com.example.demo.Impl;

import com.example.demo.dto.MbtiSubmitDTO;
import com.example.demo.entity.Student;
import com.example.demo.entity.TestRecord;
import com.example.demo.repository.StudentRepository;
import com.example.demo.repository.TestRecordRepository;
import com.example.demo.service.TestRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TestRecordServiceImpl implements TestRecordService {

    @Autowired
    private TestRecordRepository testRecordRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public void saveTestRecord(MbtiSubmitDTO dto) {
        Student student = studentRepository.findById(dto.getStudentId())
                .orElseThrow(() -> new RuntimeException("学生不存在"));

        List<TestRecord> recentRecords = testRecordRepository.findByStudent_IdOrderByTestTimeDesc(student.getId());
        if (!recentRecords.isEmpty()) {
            TestRecord lastRecord = recentRecords.get(0);
            if (lastRecord.getTestTime() != null &&
                    lastRecord.getTestTime().isAfter(LocalDateTime.now().minusSeconds(10))) {
                System.out.println("检测到重复提交，跳过保存");
                return;
            }
        }

        TestRecord record = new TestRecord();
        record.setStudent(student);
        record.setTestTime(LocalDateTime.now());
        record.setResult(dto.getType());

        testRecordRepository.save(record);
    }

}
